package com.aoip.telemetry.telemetry.configureui.business.analysis.access.service.impl;

import com.aoip.telemetry.telemetry.configureui.business.analysis.access.mapper.StInfoConfigMapper;
import com.aoip.telemetry.telemetry.configureui.business.analysis.access.service.StationAccessService;
import com.aoip.telemetry.telemetry.core.redis.RedisCache;
import com.aoip.telemetry.telemetry.entity.equipment.StInfoConfigEntity;
import com.aoip.telemetry.telemetry.entity.enums.CacheKeyEnum;
import com.aoip.telemetry.telemetry.entity.equipment.StOnlineStatusEntity;
import com.baomidou.dynamic.datasource.annotation.DS;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.Collection;
import java.util.List;

/**
 * @author chenbai
 * @version 1.0
 * @date 2021/12/27 14:42
 */
@Service
@DS("telemetry")
public class StationAccessServiceImpl implements StationAccessService {

    @Resource
    private StInfoConfigMapper stInfoMapper;
    @Resource
    private RedisCache redisCache;

    @Override
    public List<StInfoConfigEntity> list(StInfoConfigEntity entity) {
        String adCode = entity.getAdCode();
        if (StringUtils.hasText(adCode)) {
            while (adCode.endsWith("00")) {
                adCode = adCode.substring(0, adCode.length() - 2);
            }
            entity.setAdCode(adCode);
        }
        List<StInfoConfigEntity> list = stInfoMapper.list(entity);
        list.forEach(item->{
            String key = CacheKeyEnum.STATION_ONLINE_STATUS + ":" + item.getStCd();
            StOnlineStatusEntity onlineStatus = redisCache.getCacheObject(key);
            item.setOnlineStatus(onlineStatus);
        });
        return list;
    }

    @Override
    public StInfoConfigEntity station(String stcd) {
        return stInfoMapper.selectById(stcd);
    }

    @Override
    public int insert(StInfoConfigEntity entity) {
        redisCache.setCacheObject(CacheKeyEnum.STATION + ":" + entity.getStCd(), entity);
        return stInfoMapper.insert(entity);
    }

    @Override
    public int update(StInfoConfigEntity entity) {
        redisCache.setCacheObject(CacheKeyEnum.STATION + ":" + entity.getStCd(), entity);
        return stInfoMapper.updateById(entity);
    }

    @Override
    public int initCache() {
        List<StInfoConfigEntity> list = list(new StInfoConfigEntity());
        Collection<String> keys = redisCache.keys(CacheKeyEnum.STATION + ":*");
        redisCache.deleteObject(keys);
        list.forEach(item -> redisCache.setCacheObject(CacheKeyEnum.STATION + ":" + item.getStCd(), item));
        return list.size();
    }

    @Override
    public void delete(String[] stCds) {
        for (String stCd : stCds) {
            redisCache.deleteObject(CacheKeyEnum.STATION + ":" + stCd);
            stInfoMapper.deleteById(stCd);
        }
    }

}
